package com.adaxi.adc.business.vehicle.controller;


import com.adaxi.adc.business.vehicle.pojo.AdcVehicle;
import com.adaxi.adc.business.vehicle.service.AdcVehicleService;
import com.adaxi.adc.business.vehicle.utils.JwtUtil;
import com.adaxi.adc.business.vehicle.vo.adcVehicleVo;
import com.adaxi.adc.common.common.CommonResult;
import com.adaxi.adc.common.utils.UuidUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RestController
public class LoginController {

    final AdcVehicleService iadcVehicleService;

    final JwtUtil jwtUtil;

    public LoginController(AdcVehicleService iadcVehicleService, JwtUtil jwtUtil) {
        this.iadcVehicleService = iadcVehicleService;
        this.jwtUtil = jwtUtil;
    }

    @PostMapping("/login")
    public CommonResult login(@RequestBody adcVehicleVo adcVehicleVo) {
        QueryWrapper<AdcVehicle> wrapper = new QueryWrapper(); // 查询包裹体
        wrapper.eq("username", adcVehicleVo.getUsername())
               .eq("password", adcVehicleVo.getPassword());
        try {
            AdcVehicle adcVehicle = iadcVehicleService.getOne(wrapper, true);
            // 生成TOKEN
            String token = jwtUtil.generateToken(adcVehicle.getUsername());
            String vehicleMessage = String.valueOf(adcVehicle);
            HashMap<String, String> user = new HashMap<>();
            user.put("token", token);
            user.put("user", vehicleMessage);
            return CommonResult.SUCCESS("登录成功", user);

        } catch (Exception e) {
            return CommonResult.FAILURE("用户名或者密码错误");

        }
    }

    /**
     * 注册接口
     * @param adcVehicle 表单内容
     * @return 是否注册成功的信息
     */
    @PostMapping("/addVehicle")
    public CommonResult add(@RequestBody AdcVehicle adcVehicle) {
        adcVehicle.setId(UuidUtil.get32UUID());
        iadcVehicleService.save(adcVehicle);
        return CommonResult.SUCCESS("添加成功");

    }
}
